package com.wn.common.net.model

import retrofit2.Response

/**
 * @Author: wn
 * @Date: 2022/12/14 10:12
 * @Description: 密封类形式的，网络数据返回的封装类
 * -- LiveData<ApiResponse>--postValue(ApiResponse.create(response))
 * -- flow--emit(ApiResponse.create(Response))
 */
sealed class ApiResponse {
  companion object {
    // retrofit 调用 接口后 获取 Response 调用   ApiResponse=ApiResponse.create(Response) emit(create(Response))
    fun <T> create(response: Response<T>): ApiResponse {
      return if (response.isSuccessful) {
        val body = response.body()
        if (body === null || response.code() == 204)
          ApiEmptyResponse
        else
          ApiSuccessResponse(body)
      } else {
        ApiErrorResponse(
          response.code(),
          response.errorBody()?.string() ?: response.message()
        )
      }
    }

    fun create(errorCode: Int, error: Throwable): ApiResponse =
      ApiErrorResponse(
        errorCode,
        error.message ?: "Unknown Error!"
      )
  }
}

object ApiEmptyResponse : ApiResponse()

data class ApiErrorResponse(val errorCode: Int, val errorMessage: String) : ApiResponse()

data class ApiSuccessResponse<T>(val body: T) : ApiResponse()

// 未知错误码
internal const val UNKNOWN_ERROR_CODE = -1